package com.nanbei.eduService.config;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.nanbei.eduService.entity.EduSubject;
import com.nanbei.eduService.entity.excel.SubjectData;
import com.nanbei.eduService.service.EduSubjectService;
import com.nanbei.servicebase.exceptionHandler.GuliException;

public class SubjectExcelListener extends AnalysisEventListener<SubjectData> {


    //因为SubjectExcelListener不能交由Spring进行管理 只能自己new，不能自己注入
    //不能实现数据库操作
    private EduSubjectService subjectService;

    //创建该类的有参和无参构造
    public SubjectExcelListener() { }
    public SubjectExcelListener(EduSubjectService subjectService) {
        this.subjectService= subjectService;
    }


    //读取Excel内容，一行一行读取
    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
        if (subjectData == null){
            throw new GuliException(20001,"文件数据为空");
        }

        //一行一行读取 每次两个值，第一个值是一级分类，第二个值是二级分类

        //判断一级分类进行添加
        EduSubject existOneSubject = this.existOneSubject(subjectService, subjectData.getOneSubjectName());
        if (existOneSubject == null) {   //表示没有相同的一级目录，进行添加
            existOneSubject = new EduSubject();
            existOneSubject.setParentId("0");
            existOneSubject.setTitle(subjectData.getOneSubjectName());    //一级分类名称
            subjectService.save(existOneSubject);
        }

        //获取二级目录的父ID
        String pid = existOneSubject.getId();
        //判断二级分类进行添加
        EduSubject existTwoSubject = this.existTwoSubject(subjectService, subjectData.getTwoSubjectName(),pid );
        if (existTwoSubject == null) {   //表示没有相同的二级目录，进行添加
            existTwoSubject = new EduSubject();
            existTwoSubject.setParentId(pid);
            existTwoSubject.setTitle(subjectData.getTwoSubjectName());    //一级分类名称
            subjectService.save(existTwoSubject);
        }

    }

    //判断一级分类不能重复添加
    private EduSubject existOneSubject(EduSubjectService subjectService ,String name){
        QueryWrapper<EduSubject> queryWrapper= new QueryWrapper<>();
        queryWrapper.eq("title",name).eq("parent_id","0");
        EduSubject oneSubject = subjectService.getOne(queryWrapper);
        return oneSubject;
    }

    //判断二级分类不能重复添加
    private EduSubject existTwoSubject(EduSubjectService subjectService ,String name,String pid){
        QueryWrapper<EduSubject> queryWrapper= new QueryWrapper<>();
        queryWrapper.eq("title",name).eq("parent_id",pid);
        EduSubject twoSubject = subjectService.getOne(queryWrapper);
        return twoSubject;
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }


}
